from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref

from db_util import Base, Session


class User(Base):
    __tablename__ = 't_user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32))

    # articles = relationship('Article',backref='user',cascade='')
    # articles = relationship('Article',backref='user',cascade='save-update') # 默认cascade的值是save-update
    # articles = relationship('Article',backref='user',cascade='save-update,delete') # delete可以帮助删除关联表的数据
    # articles = relationship('Article',backref='user',cascade='save-update,delete,delete-orphan',single_parent=True)  # 当关联关系被解除时，子表数据会被清空


class Article(Base):
    __tablename__ = 't_article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(32))
    uid = Column(Integer, ForeignKey("t_user.id"))

    user = relationship('User', backref=backref('articles', cascade='save-update,delete,delete-orphan'))


def create_data():
    Base.metadata.drop_all()  # 删除已有的表
    Base.metadata.create_all()  # 创建表
    # 初始化数据
    user = User(name='SXT')
    art1 = Article(title='Python', uid=1)
    art2 = Article(title='MySQL', uid=1)
    user.articles.append(art1)
    user.articles.append(art2)
    # 保存数据
    with Session() as ses:
        ses.add(user)
        ses.commit()


def delete_data():
    with Session() as ses:
        user = ses.query(User).first()
        ses.delete(user)
        ses.commit()


def delete_art():
    with Session() as ses:
        art = ses.query(Article).first()
        ses.delete(art)
        ses.commit()


def update_data():
    with Session() as ses:
        user = ses.query(User).first()
        user.articles = []
        ses.commit()


if __name__ == '__main__':
    # create_data()
    # delete_data()
    # update_data()
    delete_art()






